package net.onceface.web.oauth2;

import javax.inject.Inject;

import net.onceface.application.ClientApplication;
import net.onceface.application.dto.ClientDTO;
import net.onceface.core.domain.Client;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Inject
	private ClientApplication application;
	
	/**
	 * 按用户账户查找可用的账户
	 * **/
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		ClientDTO user = application.findAvailableClientByUserAccount(username);
		if (user == null) {
			throw new UsernameNotFoundException("没有找到[" + username + "]的用户！");
		}
		return new CustomUserDetails(user);
	}

	@Override
	public Client loadCurrentUserJsonDto() {
		return null;
		/*final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		final Object principal = authentication.getPrincipal();
		if (authentication instanceof OAuth2Authentication &&
				(principal instanceof String || principal instanceof org.springframework.security.core.userdetails.User)) {
			return loadOauthUserJsonDto((OAuth2Authentication) authentication);
		}else{
			final CustomUserDetails userDetails = (CustomUserDetails) principal;
			return new ClientDTO(userRepository.findByGuid(userDetails.user().guid()));
		}*/
	}

	private ClientDTO loadOauthUserJsonDto(OAuth2Authentication authentication) {
		// TODO Auto-generated method stub
		return null;
	}

}
